/**********商品路由 router/commodity.js*******/
const express = require('express')
const pool = require('../../pool.js')
const router = express.Router()

/**********正式开始写路由***********/
//0.为分页服务：查询所有记录
//GET /getAll
router.get('/getAll', (req, res) => {
	let sql = 'select id from goods'
	pool.query(sql, (err, result) => {
		if (err) throw err
		res.send(result)
	})
})

//1.声明当前路由器下的接口：商品列表(分页，每页显示6条)
//GET  /showcommodities
//参数  页码：pno,每页显示数量:count
//返回数据：查询到的所有商品信息
//测试地址：http://127.0.0.1:端口号/commodity/showcommodities
router.get('/showcommodities', (req, res) => {
	//如果没有传参，设置默认值
	//如果页码为空，设置默认值为1
	if (req.query.pno === undefined) {
		req.query.pno = 1
	}
	//如果每页数据量为空，设置默认值5
	if (req.query.count === undefined) {
		req.query.count = 5
	}
	//计算开始查询的值
	var start = (req.query.pno - 1) * req.query.count
	//每页数据量转为数值
	var size = parseInt(req.query.count)
	let sql = 'select id,title,commodity,price,inventory,type,kind,img,ShopId,state from goods limit ?, ?'
	pool.query(sql, [start, size], (err, result) => {
		if (err) throw err;
		res.send(result)
	})
})

//3.审核商品
//put   /approve
//参数： id
//更新  isTrue=1
router.put('/approve', (req, res) => {
	let sql = `update goods set state=? where id=?`
	let id = req.query.id
	let state = '上架中'
	if (req.query.state == '0') {
		state = '审核不通过'
	}
	pool.query(sql, [state, id], (err, result) => {
		if (err) { throw err }
		if (result.affectedRows > 0) {
			res.send({ message: '审核成功！', code: 200 });
		} else {
			res.send({ message: '审核失败！', code: 201 });
		}
	})
})
//4.待审核商品列表
//为分页服务：查询所有记录
//GET /allUnapprove
router.get('/allUnapprove', (req, res) => {
	let sql = `select id from goods where state='审核中'`
	pool.query(sql, (err, result) => {
		if (err) throw err
		res.send(result)
	})
})
//5.待审核(分页，每页显示5条)
//GET  /showcommodities
//参数  页码：pno,每页显示数量:count
//测试地址：http://127.0.0.1:端口号/commodity/showUnapprove
router.get('/showUnapprove', (req, res) => {
	//如果页码为空，设置默认值为1
	if (req.query.pno === undefined) {
		req.query.pno = 1
	}
	//如果每页数据量为空，设置默认值5
	if (req.query.count === undefined) {
		req.query.count = 5
	}
	//计算开始查询的值
	var start = (req.query.pno - 1) * req.query.count
	//每页数据量转为数值
	var size = parseInt(req.query.count)
	let sql = `select id,title,commodity,price,inventory,type,kind,img,ShopId,state from goods where state='审核中' limit ?, ?`
	pool.query(sql, [start, size], (err, result) => {
		if (err) throw err;
		res.send(result)
	})
})



//导出路由器
module.exports = router